import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/purchase_item.dart';
import '../services/purchase_service.dart';
import '../providers/user_provider.dart';

class PurchasePage extends StatefulWidget {
  const PurchasePage({Key? key}) : super(key: key);

  @override
  State<PurchasePage> createState() => _PurchasePageState();
}

class _PurchasePageState extends State<PurchasePage> {
  final PurchaseService _purchaseService = PurchaseService();
  List<PurchaseItem> _items = [];
  bool _isLoading = true;
  bool _isPurchasing = false;
  String? _currentPurchaseId;

  @override
  void initState() {
    super.initState();
    _loadProducts();
    _setupPurchaseListeners();
  }

  void _setupPurchaseListeners() {
    _purchaseService.purchaseCompleteStream.listen((isComplete) {
      if (isComplete && _currentPurchaseId != null) {
        final purchaseItem = _items.firstWhere(
          (item) => item.id == _currentPurchaseId,
          orElse: () => throw Exception('Purchase item not found'),
        );
        
        if (purchaseItem.coins != null) {
          final userProvider = Provider.of<UserProvider>(context, listen: false);
          userProvider.addCoins(purchaseItem.coins!);
          
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('成功购买 ${purchaseItem.coins} 金币！'),
                backgroundColor: Colors.green,
              ),
            );
          }
        }
      }
    });
  }

  Future<void> _loadProducts() async {
    setState(() => _isLoading = true);
    try {
      await _purchaseService.initialize();
      final products = _purchaseService.products;
      setState(() {
        _items = products.map((p) => PurchaseItem.fromProductDetails(p)).toList();
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载商品失败: $e')),
        );
      }
    }
  }

  Future<void> _purchaseItem(PurchaseItem item) async {
    if (_isPurchasing) return;
    
    setState(() {
      _isPurchasing = true;
      _currentPurchaseId = item.id;
    });

    try {
      final success = await _purchaseService.purchaseProduct(item);
      if (!success) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('购买失败，请稍后重试'),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('购买失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isPurchasing = false;
          _currentPurchaseId = null;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userProvider = context.watch<UserProvider>();
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('购买'),
        actions: [
          Center(
            child: Padding(
              padding: const EdgeInsets.only(right: 16.0),
              child: Row(
                children: [
                  const Icon(Icons.monetization_on, color: Colors.amber),
                  const SizedBox(width: 4),
                  Text(
                    '${userProvider.coins}',
                    style: const TextStyle(fontSize: 16),
                  ),
                ],
              ),
            ),
          ),
          IconButton(
            icon: const Icon(Icons.restore),
            onPressed: () {
              _purchaseService.restorePurchases();
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : RefreshIndicator(
                  onRefresh: _loadProducts,
                  child: ListView.builder(
                    padding: const EdgeInsets.all(16),
                    itemCount: _items.length,
                    itemBuilder: (context, index) {
                      final item = _items[index];
                      final bool isCurrentPurchase = item.id == _currentPurchaseId;
                      
                      return Card(
                        margin: const EdgeInsets.only(bottom: 16),
                        child: ListTile(
                          title: Text(item.title),
                          subtitle: Text(item.description),
                          trailing: ElevatedButton(
                            onPressed: isCurrentPurchase || _isPurchasing
                                ? null
                                : () => _purchaseItem(item),
                            child: isCurrentPurchase
                                ? const SizedBox(
                                    width: 20,
                                    height: 20,
                                    child: CircularProgressIndicator(
                                      strokeWidth: 2,
                                    ),
                                  )
                                : Text(item.priceString),
                          ),
                        ),
                      );
                    },
                  ),
                ),
          if (_isPurchasing && _currentPurchaseId == null)
            const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }
} 